<?php
/**
 * Created By base
 * Author: Virus
 * Date: 2020/3/31
 * Time: 21:38
 */

namespace app\common\model\mysql;


use app\admin\lib\Curd;

class Config extends BaseModel
{
    use Curd;

    /**
     * 状态获取器
     * @param $value
     * @return string
     */
    public function getStatusAttr($value)
    {
        return $value ? "<i class='fa fa-check-circle'></i>" : "<i class='fa fa-close'></i>";
    }

    public function getListsOfConfig($where)
    {
        return $this->where($where)->order("id", "asc")->select();
    }

    /**
     * 保存配置
     * @param $config_id
     * @param $data
     * @return int|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function saveConfig($config_id, $data)
    {
        $res = $this->where('id', $config_id)->update($data);
        $this->putConfigFile();

        return $res;
    }

    /**
     * 将配置写入文件
     * @return bool|int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function putConfigFile()
    {
        $page_data = $this->order('id asc')->select()->toArray();
        $arr       = [];
        if (!empty($page_data)) {
            foreach ($page_data as $k => $v) {
                $name = strtoupper($v['config_name']);
                if (strtoupper($v['config_value']) == "FALSE") {
                    $v['config_value'] = false;
                }
                if (strtoupper($v['config_value']) == "TRUE") {
                    $v['config_value'] = true;
                }
                $arr[$name] = htmlspecialchars_decode($v['config_value']);
            }
        }
        // 写入配置文件
        $content = "<?php return ".var_export($arr, true)."\n?>";

        return file_put_contents("../config/site.php", $content);
    }

    /**
     * 配置参数获取器
     * @param $value
     * @return array
     */
    public function getConfigInfoAttr($value)
    {
        $info   = explode(',', $value);   // [1|开启, 0|关闭]
        $extend = [];
        foreach ($info as $k => $v) {
            $data = explode("|", $v);   // [[1,开启],[0,关闭]]

            foreach ($data as $k1 => $v1) {
                $extend[$k][$k1] = $data[$k1];
            }
        }

        return $extend;
    }
}